package com.jingtai.shop.common.config.web;

import com.jingtai.shop.filter.JwtAuthorizationTokenInterceptor;
import com.jingtai.shop.filter.NotAuthorizationTokenInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Description: Web统一配置
 * Create DateTime: 2020-03-26 13:47
 *
 * @author houyi
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${jwt.enabled}")
    private Boolean enabled;

    /**
     * 不需要认证的URI
     */
    public static final String[] NOT_AUTH_URI = {
            "/doc.html",
            "/shop/sso/userLogin",
            "/shop/sso/userRegister",
            "/shop/sso/userObtainCode",
            "/shop/sso/userForgetPwd",
            "/shop/carousel/listShufflingFigure",
            "/shop/goods/listCategoryByLevelOne",
            "/shop/goods/listGoodsCategoryLevelTwo",
            "/shop/goods/pageGoodsByLevel",
            "/shop/goods/pageGoodsByRecommend",
            "/shop/goods/queryGoodsDetail",
            "/shop/goods/searchMerchantsGoods",
            "/shop/goods/showShopAttribute",
    };

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 添加拦截器，配置拦截地址
        if (enabled) {
            registry.addInterceptor(jwtAuthorizationTokenInterceptor())
                    .addPathPatterns("/**")
                    .excludePathPatterns(NOT_AUTH_URI);
        } else {
            registry.addInterceptor(NotAuthorizationTokenInterceptor())
                    .addPathPatterns("/**");
        }

    }

    @Bean
    @ConditionalOnProperty(prefix = "jwt", name = "enabled", havingValue = "true")
    public HandlerInterceptor jwtAuthorizationTokenInterceptor() {
        return new JwtAuthorizationTokenInterceptor();
    }

    @Bean
    @ConditionalOnProperty(prefix = "jwt", name = "enabled", havingValue = "false")
    public HandlerInterceptor NotAuthorizationTokenInterceptor() {
        return new NotAuthorizationTokenInterceptor();
    }
}
